﻿using System;
using System.IO;
using System.Text;
using System.Web;
using System.Diagnostics;

namespace GateKeeper
{
    public static class debug
    {
        public static void LogIt(string message, EventType eventType)
        {
            if (!GateKeeperModule.config.EnableDebugLogging) { return; }
            if (string.IsNullOrEmpty(message)) { return; }

            string path = HttpContext.Current.Server.MapPath("~/app_data/" + GateKeeperModule.config.DebugLogFileName);
            string line = string.Format("{0} : {1} : {2}", DateTime.Now, eventType.ToString().ToUpper(), message);

            object _SyncRoot = new object();
            try
            {
                lock (_SyncRoot)
                {
                    if (File.Exists(path))
                    {
                        using (StreamWriter sw = File.AppendText(path))
                        {
                            sw.WriteLine(line);
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = File.CreateText(path))
                        {
                            sw.WriteLine(line);
                            sw.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            { throw ex; }
        }

        public static void LogIt(string message)
        { LogIt(message, EventType.information); }
        
        public static void LogIt(HttpContext current)
        {
            LogIt("Request Method: " + current.Request.HttpMethod, EventType.information);
            LogIt("Requested URL: " + current.Request.Url.AbsoluteUri, EventType.information);
            LogIt("IPAddress: " + current.Request.UserHostAddress, EventType.information);
            if (current.Request.UserAgent != null) 
                { LogIt("UserAgent: " + current.Request.UserAgent, EventType.information); }
            if (current.Request.UrlReferrer != null) 
                { LogIt("Referrer: " + current.Request.UrlReferrer.AbsoluteUri, EventType.information); }
        }

        public static void LogIt(Exception ex, string functionName)
        {
            LogIt("An exception occurred in " + functionName, EventType.critical);
            LogIt(ex.Message, EventType.critical);
            LogIt(ex.StackTrace, EventType.critical);
        
        }

        public enum EventType
        { information, warning, error, critical, requeststarted, requestallowed, requestdenied }
    }
}
